using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Xml;

namespace MIS.EN.Exchange.Parsers
{
    internal static class WebDavResultValueParserFactory
    {
        private static Dictionary<string, IWebDavResultValueParser> parsers;
        private static Dictionary<string, string> parserMappings;
        private static Assembly executingAssembly;
 
        static WebDavResultValueParserFactory()
        {
            WebDavResultValueParserFactory.parsers = new Dictionary<string, IWebDavResultValueParser>();
            WebDavResultValueParserFactory.parserMappings = new Dictionary<string, string>();
            WebDavResultValueParserFactory.executingAssembly = Assembly.GetExecutingAssembly();
            WebDavResultValueParserFactory.LoadParserMappings();
        }

        public static IWebDavResultValueParser GetWebDavResultValueParser(string type)
        {
            IWebDavResultValueParser parser = null;
            string parserTypeName = WebDavResultValueParserFactory.parserMappings[type];
            if (WebDavResultValueParserFactory.parsers.ContainsKey(parserTypeName))
            {
                parser = WebDavResultValueParserFactory.parsers[parserTypeName];
            }
            else
            {
                parser = WebDavResultValueParserFactory.executingAssembly.CreateInstance(parserTypeName, true) as IWebDavResultValueParser;
                if (parser != null)
                {
                    WebDavResultValueParserFactory.parsers.Add(parserTypeName, parser);
                }
            }
            return parser;
        }

        private static void LoadParserMappings()
        {
            XmlDocument parserMappingsDocument = new XmlDocument();
            parserMappingsDocument.Load(WebDavResultValueParserFactory.executingAssembly.GetManifestResourceStream("MIS.EN.Exchange.Parsers.ParserTypeMappings.xml"));
            XmlNodeList parserMappings = parserMappingsDocument.SelectNodes("/parserTypeMappings/parserTypeMapping");
            foreach (XmlNode parserMapping in parserMappings)
            {
                WebDavResultValueParserFactory.parserMappings.Add(parserMapping.Attributes.GetNamedItem("type").Value,
                    parserMapping.Attributes.GetNamedItem("parserType").Value);
            }
        }
    }
}
